package sub

import (
	"fmt"
	"quipus/cmd/qpc/sub"
	"quipus/internal/utils"
	v1pb "quipus/proto/gen/api/v1"
	"strings"

	"github.com/spf13/cobra"
)

var (
	commmand  string
	llm       int32
	embedding int32
)

func init() {
	// sub.RegisterCommonFlags(tenantCmd)

	ctrCmd.PersistentFlags().Int32VarP(&id, "id", "i", 100, "list limit")
	ctrCmd.PersistentFlags().StringVar(&commmand, "cmd", "", "ctrl granary cmd:start stop")
	ctrCmd.PersistentFlags().Int32VarP(&embedding, "embedding", "e", 0, "embedding model id")
	ctrCmd.PersistentFlags().Int32VarP(&llm, "llm", "l", 0, "llm model id")
	granaryCmd.AddCommand(ctrCmd)
}

var ctrCmd = &cobra.Command{
	Use:   "ctr",
	Short: "Run ctr for a granary",
	RunE: func(cmd *cobra.Command, args []string) error {
		qconn, e := sub.NewGrpcConnect(sub.QpConfig.QPAddress)
		if e != nil {
			return e
		}

		qclient := v1pb.NewGranaryServiceClient(qconn)
		ctxWithToken := sub.NewCtxWithToken(sub.QpConfig.Token)
		urn := utils.BuildUrn(utils.GranaryUrnPrefix, id)

		in := &v1pb.CtrlGranaryRequest{Urn: urn}
		if commmand == "" {
			return fmt.Errorf("command is required")
		}

		gcmd := v1pb.GranaryCmd(v1pb.GranaryCmd_value[strings.ToUpper(commmand)])
		in.Cmd = gcmd
		if gcmd == v1pb.GranaryCmd_START {
			in.LlmModel = utils.BuildUrn(utils.ModelUrnPrefix, llm)
			in.EmbeddingModel = utils.BuildUrn(utils.ModelUrnPrefix, embedding)
		}

		rsp, err := qclient.CtrlGranary(ctxWithToken, in)
		if err != nil {
			return err
		}

		fmt.Print(rsp)
		return nil
	},
}
